package com.sfang.common.base.http.Interceptor;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

import com.sfang.common.base.response.Response;

/**
 * 拦截响应
 * <p>
 * 可对响应值做修改
 * </p>
 *
 * @author xuzilou
 * @date 2021/3/25 16:53
 */
@ControllerAdvice
@Slf4j
public class InterceptResponse implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        try {

            /*if (body instanceof Response) {
                String traceId = MDC.get("traceId");
                if (StringUtils.isEmpty(((Response) body).getTraceId())
                        && StringUtils.isNotEmpty(traceId)) {
                    ((Response) body).setTraceId(traceId);
                }
            }*/

            ServletServerHttpRequest httpServletRequest = (ServletServerHttpRequest) request;
            HttpServletRequest servletRequest = httpServletRequest.getServletRequest();
            servletRequest.setAttribute("response_xzl", JSONUtil.toJsonStr(body));
        } catch (Exception e) {
            log.info("print log error:{}", e.getMessage());
        }
        return body;
    }
}
